package com.dtruth.dataflow.mq;

import java.io.Serializable;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import com.dtruth.dataflow.util.Env;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 创建
 * @author 岳海亮
 * @email yhl@feheadline.com
 * @date 2015年1月8日
 */
public class ConnectionConfig implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	// Use named parameters
	private String host;
	private int port;
	private String username;
	private String password;
	private String virtualHost;
	private int heartBeat;

	// Use AMQP URI http://www.rabbitmq.com/uri-spec.html
	private String uri;

	public ConnectionConfig(String uri) {
		this.uri = uri;
	}

	public ConnectionConfig() {
		host = Env.getInstance().getProperty("rabbitmq.host", "tree");
		port = Integer.parseInt(Env.getInstance().getProperty("rabbitmq.port",
				"5672"));
		username = Env.getInstance().getProperty("rabbitmq.username", "fenews");
		password = Env.getInstance().getProperty("rabbitmq.password", "fenews");
		virtualHost = Env.getInstance().getProperty("rabbitmq.virtualhost",
				"fenews");
		heartBeat = 10;
	}

	public ConnectionConfig(String host, String username, String password) {
		this(host, ConnectionFactory.DEFAULT_AMQP_PORT, username, password,
				ConnectionFactory.DEFAULT_VHOST, 10);
	}

	public ConnectionConfig(String host, int port, String username,
			String password, String virtualHost, int heartBeat) {
		this.host = host;
		this.port = port;
		this.username = username;
		this.password = password;
		this.virtualHost = virtualHost;
		this.heartBeat = heartBeat;
	}

	public String getHost() {
		return host;
	}

	public int getPort() {
		return port;
	}

	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	public String getVirtualHost() {
		return virtualHost;
	}

	public int getHeartBeat() {
		return heartBeat;
	}

	public String getUri() {
		return uri;
	}

	public ConnectionFactory asConnectionFactory() {
		ConnectionFactory factory = new ConnectionFactory();
		if (uri != null) {
			try {
				factory.setUri(uri);
			} catch (URISyntaxException e) {
				throw new RuntimeException(e);
			} catch (NoSuchAlgorithmException e) {
				throw new RuntimeException(e);
			} catch (KeyManagementException e) {
				throw new RuntimeException(e);
			}
		} else {
			factory.setHost(host);
			factory.setPort(port);
			factory.setUsername(username);
			factory.setPassword(password);
			factory.setVirtualHost(virtualHost);
			factory.setRequestedHeartbeat(heartBeat);
		}
		return factory;
	}
}